package cn.tedu.sp06.filter;


import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


@Component
public class LoginFilter extends ZuulFilter {
    /*
    过滤器类型: pre,routing,post,error
     */

    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;//前置过滤器
    }

    /*
    位置顺序号 zuul的前置过滤器默认已经有5个
     */
    @Override
    public int filterOrder() {
        return 6; //放到末尾
    }

    /*
    判断针对当前请求,是否要执行过滤代码
     */
    @Override
    public boolean shouldFilter() {
        /*
        设置 item=service 需要检查权限
        调用其它服务部判断权限,可以直接访问
         */

        //获取当前请求调用的服务id
        RequestContext ctx = RequestContext.getCurrentContext(); //上下文对象
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);

        //判断id是不是"item-service"
        return  "item-service".equalsIgnoreCase(serviceId);
        //equalsIgnoreCase不区分大小写
    }

    /*
    过滤代码
     */
    @Override
    public Object run() throws ZuulException {
        //http://localhost:3001/item-service/d32454?token=3edd

        //得到request 对象(获取token参数)
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();


        //用request接收 token参数
        String token = request.getParameter("token");

        //如果收不到 token, 阻止向后台服务转发,直接向客户端返回响应
        if (StringUtils.isBlank(token)){
            //阻止向后台服务转发
            ctx.setSendZuulResponse(false);

            //向客户端直接发送响应: JsonResult = {code:400,msg:"not login!",data :null}
            String json =
                    JsonResult.err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("Not Login! 没有登录!")
                    .toString();
            //http 协议头属性, Content-Type: application/json;charset=UTF-8
            ctx.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8");
            ctx.setResponseBody(json);


        }
        return null; //当前zuul版本中,没有使用这个返回值
    }
}
